package com.joinway.framework.extension.console;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FilenameUtils;

public final class FileAccessUtils {

	public static final int BUFFER = 1024;
	
	/**
	 * 
	 * @param inputStream
	 * @param outFile	output file path and name, e.g. /tmp/demo.txt
	 * @throws IOException 
	 */
	public static void write(InputStream inputStream, String outFile) throws IOException{
		write(inputStream, outFile, BUFFER);
	}
	
	/**
	 * 
	 * @param inputStream
	 * @param outFile	output file path and name, e.g. /tmp/demo.txt
	 * @param buffer	buffer size
	 * @throws IOException
	 */
	public static void write(InputStream inputStream, String outFile, int buffer) throws IOException{
		String dir = FilenameUtils.getFullPath(outFile);
		org.apache.commons.io.FileUtils.forceMkdir(new File(dir));
		
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile));
		
		byte[] data = new byte[buffer];
		int len = 0;
		while((len = inputStream.read(data)) != -1){
			bos.write(data, 0, len);
		}
		
		bos.flush();
		bos.close();
		inputStream.close();
	}
}

